package com.yuyou.fn.settlement.service.impl;

import com.github.wens.mybatisplus.examples.Example;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BigDecimals;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.settlement.service.IMainAccountService;
import org.springframework.stereotype.Service;

import com.yuyou.fn.settlement.mapper.BalanceLockRecordMapper;
import com.yuyou.fn.settlement.entity.BalanceLockRecord;
import com.yuyou.fn.settlement.service.IBalanceLockRecordService;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 *
 * BalanceLockRecord 表数据服务层接口实现类
 *
 */
@Service
public class BalanceLockRecordServiceImpl extends SuperServiceImpl<BalanceLockRecordMapper, BalanceLockRecord,Long> implements IBalanceLockRecordService {

    @Resource
    private IMainAccountService mainAccountService ;

    @Transactional
    @Override
    public void lock(Long mainAccountId, String lockKey , BigDecimal amount , String remark ) {

        if( amount == null || BigDecimals.compare(amount,BigDecimal.ZERO) == 0 ){
            return;
        }

        if( mainAccountService.lockBalanceAmount(mainAccountId,amount)){
            BalanceLockRecord balanceLockRecord  = new BalanceLockRecord() ;
            balanceLockRecord.setMainAccountId(mainAccountId);
            balanceLockRecord.setAmount(amount);
            balanceLockRecord.setLockKey(lockKey);
            balanceLockRecord.setRemark(remark);
            balanceLockRecord.setCreateTime(TimeUtils.now());
            balanceLockRecord.setUpdateTime(TimeUtils.now());
            insertSelective(balanceLockRecord) ;
        }else{
            throw new BusException("锁定失败,余额不足扣减");
        }

    }

    @Transactional
    @Override
    public void unlock(Long mainAccountId , String lockKey, BigDecimal amount ) {

        if( amount == null || BigDecimals.compare(amount,BigDecimal.ZERO) == 0 ){
            return;
        }

        Example<BalanceLockRecord> example = BalanceLockRecord.createExample();
        example.createCriteria().andEqualTo("lockKey" , lockKey );
        boolean b = deleteByExample(example);
        if(b){
            mainAccountService.unlockBalanceAmount(mainAccountId,amount) ;
        }else{
            throw new BusException("解锁失败,找不到对应的账户锁定记录");
        }
    }
}